package ks.server.controllers.commands.general.table;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.debug.Debug;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.server.ipc.Listener;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * 
 * @author szutshi
 *
 */

public class TableChatController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public TableChatController (Communicator com) {
		this.com = com;
	}
	
	public boolean process(Message m) {
		
		
		Node text = m.contentsChild();
		if (text == null) {
			return false;
		}
		
        String s = text.getTextContent();
        
		NamedNodeMap nnp = m.contents().getAttributes();
		Node tableNode = nnp.getNamedItem("table");
		
		if (tableNode == null) {
			Listener.nack(m, 4, "tableNode null.");
			return false;
		}
		
		String player = m.getOriginator();
		int tableNum = Integer.parseInt(tableNode.getNodeValue());
		
		Listener.ack(m, "a");
		
        // produce request.
        StringBuilder sb = new StringBuilder("<request version='1.0' id='589a39591271844e3fbe32bbb9281ad9'>");
        sb.append("<table-output table=\"" + tableNum + "\" player=\"" + player + "\" >");
        sb.append("<text>" + s + "</text>");
        sb.append("</table-output>");
        sb.append("</request>");
        Document d = Message.construct(sb.toString());
        
        // send to all clients EXCEPT self.
        Message r = new Message (d);
        r.setBroadcast();
        
        Debug.println("sending table-output....");
        
        return com.distribute(r);
	}
}